package com.neu.Dao;

import com.neu.util.DBUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
//抽象类不能被实例化

public abstract class BaseDao {
    protected Connection conn;
    protected PreparedStatement pstm;
    protected ResultSet rst;
    protected final void close(){
        DBUtil.close(rst,pstm,conn);
    }
    protected final void getConnection() throws SQLException {
        conn = DBUtil.getConnection();
    }

    protected final int executeUpdate(final String sql,String...args){
        int row = 0;
        try {
            getConnection();
            pstm = conn.prepareStatement(sql);
            if (args!=null){
                for (int i = 0; i < args.length ; i++) {
                    pstm.setString(i+1,args[i]);
                }
            }
            row = pstm.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            close();
        }

        return row;
    }
    protected final List<Map<String,Object>> executeQuery(final String sql,String...args){
        List<Map<String,Object>> list = new ArrayList<>();
        //啊，还没写呢
        try {
            getConnection();
            pstm = conn.prepareStatement(sql);
            if(args!=null){
                for (int i = 0; i < args.length; i++) {
                    pstm.setString(i+1,args[i]);
                }
            }
            rst = pstm.executeQuery();

            ResultSetMetaData meta = rst.getMetaData();
            int n = meta.getColumnCount();
            String[] names=new String[n];
            for(int i=0;i<n;i++){
                names[i]=meta.getColumnLabel(i+1);
            }
            while (rst.next()){
                Map<String,Object> book = new HashMap<>();
                for (int i = 0; i < n; i++) {
                    String key = meta.getColumnLabel(i+1);
                    Object value = rst.getObject(i+1);
                    book.put(key,value);

                }

                list.add(book);

            }



        } catch (SQLException e) {
            e.printStackTrace();
        }


        return list;
    }


}
